<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Chat Room</title>
    <script src="https://cdn.jsdelivr.net/npm/protobufjs/dist/protobuf.min.js"></script>
    <script type="text/javascript">
        var socket;
        var userName = "ssss";

        // 加载 Protobuf 定义文件
        var ChatMessageProto;

        protobuf.load("/chat.proto", function (err, root) {
            if (err) throw err;
            ChatMessageProto = root.lookupType("ChatMessage");
        });

        function connect() {
            socket = new WebSocket("ws://127.0.0.1:8080/ws");
            socket.binaryType = "arraybuffer";

            socket.onmessage = function (event) {
                var buffer = new Uint8Array(event.data);
                var message = ChatMessageProto.decode(buffer);

                var user = message.user;
                var msg = message.message;
                var timestamp = message.timestamp;

                document.getElementById("messages").innerHTML += user + ": " + msg + " (" + timestamp + ")<br/>";
            };

            socket.onopen = function (event) {
                sendMessage("joined the chat");
            };

            socket.onclose = function (event) {
                document.getElementById("messages").innerHTML += "Connection closed<br/>";
            };
        }

        function sendMessage(msg) {
            var timestamp = new Date().toLocaleTimeString();

            // 创建 Protobuf 消息对象
            var messageObj = {
                user: userName,
                message: msg,
                timestamp: timestamp
            };

            // 编码为二进制数据
            var errMsg = ChatMessageProto.verify(messageObj);
            if (errMsg) throw Error(errMsg);

            var messageBuffer = ChatMessageProto.encode(ChatMessageProto.create(messageObj)).finish();
            socket.send(messageBuffer);
        }

        window.onload = function () {
            connect();
        };
    </script>
</head>
<body>
<div id="messages"></div>
<input type="text" id="message" placeholder="Enter message"/>
<button onclick="sendMessage(document.getElementById('message').value)">Send</button>
</body>
</html>
